
import { Flex } from '@/components/flex';
import { Form } from '@/components/base';
import { formScrollToError } from '@/utils/funs';
import * as UI from './ui'
import * as hooks from './hooks'
import * as apis from '@shared/apis'
import styles from './index.module.less';
import React from 'react';
import * as pages from '@/pages';
import { Controller } from '@/views/basic-layout/controller';
import { useNavigate } from 'react-router-dom';

export default function CustomerForm() {
    const { id } = hooks.useSearch();
    return (
        <Body key={id || new Date().getTime()} />
    )
}

function Body() {
    const controller = React.useContext(Controller.Context);
    const { isEdit, id } = hooks.useSearch();
    const [form] = Form.useForm();
    const navigator = useNavigate();

    React.useEffect(() => {
        if (isEdit) {
            apis.customers.detail.get(id).then(data => {
                form.setFieldsValue(data);
            });
        } else {
            // 初始 客户编号 日期(YYYYMMDD) + 随机数(大写)
            const code = `001-${new Date().getFullYear()}${new Date().getMonth() + 1}${new Date().getDate()}-${Math.random().toString(36).substring(2, 15).toUpperCase()}`;
            form.setFieldsValue({ code });
        }
    }, [isEdit, form, controller, id])

    const handleSave = async () => {
        try {
            const values = await form.validateFields();
            const data = isEdit
                ? await apis.customers.update.post({ ...values, id })
                : await apis.customers.create.post(values);

            controller.removeTab(pages.customerManagement.name);
            controller.removeTab(pages.customerDetail.name);
            navigator(`/${pages.customerDetail.name}?id=${data.id}`, { replace: true })
        } catch (error) {
            // 调整滚动条，显示错误得表单
            formScrollToError(error);
        }
    }

    return (
        <Flex vertical style={{ backgroundColor: '#f5f5f5', height: '100vh' }}>
            <UI.Header onSave={handleSave} />
            <Form className={styles['form']} layout='vertical' requiredMarkStyle='asterisk' form={form}>
                <UI.BasicInfoForm />
                <UI.ScalpInfoForm />
            </Form>
        </Flex>
    );
}
